package com.dreamcode.anfeedreader.activity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.dreamcode.anfeedreader.collectors.FeedListAdapter;
import com.dreamcode.anfeedreader.collectors.FeedsDAOimpl;
import com.dreamcode.anfeedreader.modelClass.Feed;
import com.dreamcode.anfeedreader.modelClass.FeedItem;
import com.dreamcode.anfeedreader.utils.DateUtils;
import com.dreamcode.anfeedreader.utils.FeedParser;
import com.dreamcode.anfeedreader.utils.Message;
import com.dreamcode.anfeedreader.utils.XmlPullFeedParser;


public class FeedItemListActivity extends Activity {

  private FeedsDAOimpl feedItemsDAO = null;
  private FeedItem feedItem = null;
  private ListView feedList = null;
  private Button btnBack = null;
  private Button btnrefresh = null;
  private TextView textView = null;
  private Bundle bundle  = null;
  private FeedParser parser = null;	
  private List<Message> messages;
  private Message feedMessage = null;
  private ProgressDialog progDialog = null; 
  private Handler handler = new Handler();
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      //requestWindowFeature(Window.FEATURE_NO_TITLE);
      setContentView(R.layout.feeditemslist);
      initView();
  }

	@Override
	protected void onResume() {		
		feedList.setAdapter(new FeedListAdapter(FeedItemListActivity.this,
				feedItemsDAO.getAllFeedItemsFromDB(FeedItemListActivity.this,bundle.getInt("id"))));
		feedList.setAnimationCacheEnabled(true);
		super.onResume();
	}

private void initView() {
	bundle = getIntent().getExtras();
	textView = (TextView) findViewById(R.id.feed_title);
	feedItemsDAO = FeedsDAOimpl.getInstance();
	textView.setBackgroundColor(Color.DKGRAY);
	textView.setText(feedItemsDAO.getFeed(FeedItemListActivity.this, bundle.getInt("id")).getTitle());
	btnBack =(Button) findViewById(R.id.btnback);
	btnrefresh = (Button) findViewById(R.id.btnarefresh);
	btnrefresh.setOnClickListener(new OnClickListener() {

		@Override
		public void onClick(View v) {
			progDialog = ProgressDialog.show(FeedItemListActivity.this, "", (CharSequence)Html.fromHtml(getString(R.string.update_wait)), true);
			handler.postDelayed(updatingRunnable,1000);
//			updateAllFeedItems(feedItemsDAO.getFeed(FeedItemListActivity.this, bundle.getInt("id")));				
		}

	});
	btnBack.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			finish();				
		}
	});
	feedList = (ListView) findViewById(R.id.itemlist);		
	feedList.setAdapter(new FeedListAdapter(FeedItemListActivity.this,
			feedItemsDAO.getAllFeedItemsFromDB(FeedItemListActivity.this,bundle.getInt("id"))));
	feedList.setOnItemClickListener(new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {			
			Intent i = new Intent(FeedItemListActivity.this,FeedItemViewActivity.class);
            i.putExtra("id", arg1.getId());
            startActivity(i);
			
		}
	});

  }
private Runnable updatingRunnable = new Runnable() {
	
	public void run() {
		//ProgressDialog dialog = ProgressDialog.show(AnFeedReader.this, "", (CharSequence)Html.fromHtml(getString(R.string.update_wait)), true);
		updateAllFeedItems(feedItemsDAO.getFeed(FeedItemListActivity.this, bundle.getInt("id")));
		progDialog.dismiss();
		initView();
	}
};

	private void updateAllFeedItems(Feed feed) {
		Date crDate = null;
		String formatedDate;
		SimpleDateFormat sdFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm zzzz");
		List<FeedItem> feedItems = feedItemsDAO.getAllFeedItemsFromDB(FeedItemListActivity.this, feed.getId());
		if (feedItems.size() > 0) {
			Iterator iterator = feedItems.iterator();
			if (feed.getUrl() != null) {
				parser = new XmlPullFeedParser(feed.getUrl());
				messages = parser.parse();
				if(messages!=null && messages.size()>0) {
					crDate = new Date();
					formatedDate = sdFormat.format(crDate);
					for (int i = 0; i < messages.size(); i++) {
						feedMessage = messages.get(i);
						if(feedMessage.getTitle()!=null && feedMessage.getLink()!=null) {								
							feedItem = new FeedItem();
							feedItem.setTitle(feedMessage.getTitle());
							feedItem.setDescription(feedMessage.getDescription());
							feedItem.setLink(feedMessage.getLink().toString());
							feedItem.setPubDate(DateUtils.formatDate(DateUtils.parseDate((feedMessage.getDate()!=null)?feedMessage.getDate():formatedDate)));
							feedItem.setFeed_id(feed.getId());
							feedItem.setMd5hash(feedItemsDAO.getMd5Hash(feedItem.getLink()));
							feedItem.setStatus("0");
							if(!feedItemsDAO.checkItemExistence(this,feedItem)) {
								feedItemsDAO.insertFeedItems(this, feedItem);
							}
						}
					}
				}
				else {
					AlertDialog groupDialog = new AlertDialog.Builder(FeedItemListActivity.this).setTitle(R.string.invalid_url)
					.setMessage(R.string.invalid_url_message + feed.getUrl() + R.string.check_it_again)
					.setPositiveButton(R.string.ok, null).show();
					initView();
				}
			}
		}
	}

}
